/*
 * Copyright (C) 2012-2013 Michael L.R. Marques
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * Contact: michaellrmarques@gmail.com
 */
package com.jm.jmsql.database;

import com.jm.commons.logging.LogSystem;
import com.jm.commons.ui.UIBounds;
import com.jm.jmsql.models.DatabaseComboBoxModel;
import com.jm.jmsql.objects.Database;
import com.jm.jmsql.objects.Definition;
import com.jm.jmsql.objects.events.DefinitionEvent;
import com.jm.jmsql.objects.events.DefinitionTestConnectionAdapter;
import com.jm.jmsql.utils.Constants;
import java.awt.Frame;
import java.io.IOException;
import java.sql.SQLException;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @author Michael L.R. Marques
 */
public class DefinitionManager extends javax.swing.JDialog implements DocumentListener {
    
    /**
     * 
     */
    public static final int SUCCESSFUL = 1;
    
    /**
     * 
     */
    public static final int UN_SUCCESSFUL = 0;
    
    /**
     * 
     */
    private int option;
    
    /**
     * Creates new form DefinitionManager
     * @param parent
     * @param database 
     */
    public DefinitionManager(Frame parent, Database database) {
        super(parent);
        initComponents();
        this.mainPanel.setImage(new java.io.File("./images/optionslogo.png"));
        UIBounds.setBounds(parent, this);
        // Set the icon image
        try {
            setIconImage(ImageIO.read(getClass().getClassLoader().getResource("com/jm/jmsql/icons/connected_definition.png")));
        } catch (IOException ioe) {
            LogSystem.log(getClass(), getClass().getEnclosingMethod(), "Set the icon image", ioe);
        }
        // 
        this.txtDefinitionName.getDocument().addDocumentListener(this);
        this.txtDatasource.getDocument().addDocumentListener(this);
        this.txtUsername.getDocument().addDocumentListener(this);
        this.txtPassword.getDocument().addDocumentListener(this);
        // 
        this.cbxDatabases.setModel(new DatabaseComboBoxModel(database));
    }
    
    /**
     * 
     * @param definition
     */
    public void setDefinition(Definition definition) {
        this.txtDefinitionName.setText(definition.getName());
        this.txtDatasource.setText(definition.getDatasource());
        this.txtUsername.setText(definition.getUsername());
        this.txtPassword.setText(definition.getPassword());
        this.cbxDatabases.setSelectedItem(definition.getDatabase());
        
        this.txtDefinitionName.setEditable(false);
        this.btnTestDatasource.setEnabled(true);
        this.btnDone.setEnabled(true);
    }
    
    /**
     * 
     * @return 
     */
    public Definition getDefinition() {
        return this.option == SUCCESSFUL ? new Definition((Database) this.cbxDatabases.getSelectedItem(), this.txtDefinitionName.getText(), this.txtDatasource.getText(), this.txtUsername.getText(), new String(this.txtPassword.getPassword())) : null;
    }
    
    /**
     * 
     * @return 
     */
    public int showDialog() {
        this.option = UN_SUCCESSFUL;
        setVisible(true);
        return this.option;
    }
    
    /**
     * 
     * @param e 
     */
    @Override public void insertUpdate(DocumentEvent e) {
        this.btnTestDatasource.setEnabled(!this.txtDefinitionName.getText().isEmpty() &&
                                    !this.txtDatasource.getText().isEmpty() &&
                                        !this.txtUsername.getText().isEmpty() &&
                                            !(new String(this.txtPassword.getPassword())).isEmpty() &&
                                                this.cbxDatabases.getSelectedItem() != null);
        this.btnDone.setEnabled(!this.txtDefinitionName.getText().isEmpty() &&
                                    !this.txtDatasource.getText().isEmpty() &&
                                        !this.txtUsername.getText().isEmpty() &&
                                            !(new String(this.txtPassword.getPassword())).isEmpty() &&
                                                this.cbxDatabases.getSelectedItem() != null);
    }
    
    /**
     * 
     * @param e 
     */
    @Override public void removeUpdate(DocumentEvent e) {
        this.btnTestDatasource.setEnabled(!this.txtDefinitionName.getText().isEmpty() &&
                                    !this.txtDatasource.getText().isEmpty() &&
                                        !this.txtUsername.getText().isEmpty() &&
                                            !(new String(this.txtPassword.getPassword())).isEmpty() &&
                                                this.cbxDatabases.getSelectedItem() != null);
        this.btnDone.setEnabled(!this.txtDefinitionName.getText().isEmpty() &&
                                    !this.txtDatasource.getText().isEmpty() &&
                                        !this.txtUsername.getText().isEmpty() &&
                                            !(new String(this.txtPassword.getPassword())).isEmpty() &&
                                                this.cbxDatabases.getSelectedItem() != null);
    }
    
    /**
     * 
     * @param e 
     */
    @Override public void changedUpdate(DocumentEvent e) {
        this.btnTestDatasource.setEnabled(!this.txtDefinitionName.getText().isEmpty() &&
                                    !this.txtDatasource.getText().isEmpty() &&
                                        !this.txtUsername.getText().isEmpty() &&
                                            !(new String(this.txtPassword.getPassword())).isEmpty() &&
                                                this.cbxDatabases.getSelectedItem() != null);
        this.btnDone.setEnabled(!this.txtDefinitionName.getText().isEmpty() &&
                                    !this.txtDatasource.getText().isEmpty() &&
                                        !this.txtUsername.getText().isEmpty() &&
                                            !(new String(this.txtPassword.getPassword())).isEmpty() &&
                                                this.cbxDatabases.getSelectedItem() != null);
        
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new com.jm.commons.components.panel.ImagePanel();
        btnDone = new javax.swing.JButton();
        txtUsername = new com.jm.commons.components.textfield.HintJTextField();
        txtDatasource = new com.jm.commons.components.textfield.HintJTextField();
        cbxDatabases = new javax.swing.JComboBox();
        txtPassword = new javax.swing.JPasswordField();
        txtDefinitionName = new com.jm.commons.components.textfield.HintJTextField();
        btnTestDatasource = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Definition Manager");
        setLocationByPlatform(true);
        setModal(true);
        setResizable(false);

        mainPanel.setImage(new java.io.File("C:\\Users\\Michael\\Documents\\NetBeansProjects\\JMSql\\images\\optionslogo.png"));
        mainPanel.setPreferredSize(new java.awt.Dimension(549, 227));

        btnDone.setText("Done");
        btnDone.setEnabled(false);
        btnDone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                done(evt);
            }
        });

        txtUsername.setHintText("Username...");
        txtUsername.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                done(evt);
            }
        });

        txtDatasource.setHintText("Datasource...");
        txtDatasource.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                done(evt);
            }
        });

        txtPassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                done(evt);
            }
        });

        txtDefinitionName.setHintText("Definition Name...");
        txtDefinitionName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                done(evt);
            }
        });

        btnTestDatasource.setText("Test Datasource");
        btnTestDatasource.setEnabled(false);
        btnTestDatasource.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                testDatasource(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtDefinitionName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(btnTestDatasource)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnDone))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(163, 163, 163)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtPassword)
                            .addComponent(txtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE))
                        .addGap(163, 163, 163))
                    .addComponent(cbxDatabases, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtDatasource, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(103, 103, 103)
                .addComponent(txtDefinitionName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cbxDatabases, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addComponent(txtDatasource, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnDone)
                    .addComponent(btnTestDatasource))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void done(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_done
        // Done button must be enabled
        if (!this.btnDone.isEnabled()) {
            return;
        }
        // Set the option as successful
        this.option = SUCCESSFUL;
        
        // Hide the definition manager
        setVisible(false);
    }//GEN-LAST:event_done

    private void testDatasource(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testDatasource
        Definition definition = new Definition((Database) this.cbxDatabases.getSelectedItem(), this.txtDefinitionName.getText(), this.txtDatasource.getText(), this.txtUsername.getText(), new String(this.txtPassword.getPassword()));
        definition.addDefinitionListener(new DefinitionTestConnectionAdapter() {
            @Override
            public void connectionSuccessful(DefinitionEvent e) {
                JOptionPane.showMessageDialog(rootPane, "The connection to the datasource was successful", "Test Datasource Successful", JOptionPane.INFORMATION_MESSAGE);
            }
            @Override
            public void connectionFailed(DefinitionEvent e) {
                SQLException sqle = e.getDefinition().getException();
                String exceptionMessage = "SQL Error Code: " + sqle.getErrorCode() + Constants.NEW_LINE + "SQL State: " + sqle.getSQLState() + Constants.NEW_LINE + "Message: " + sqle.getMessage();
                JOptionPane.showMessageDialog(rootPane, exceptionMessage, "Test Datasource Unsuccessful", JOptionPane.ERROR_MESSAGE);
            }
        });
        definition.connect();
    }//GEN-LAST:event_testDatasource
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDone;
    private javax.swing.JButton btnTestDatasource;
    private javax.swing.JComboBox cbxDatabases;
    private com.jm.commons.components.panel.ImagePanel mainPanel;
    private com.jm.commons.components.textfield.HintJTextField txtDatasource;
    private com.jm.commons.components.textfield.HintJTextField txtDefinitionName;
    private javax.swing.JPasswordField txtPassword;
    private com.jm.commons.components.textfield.HintJTextField txtUsername;
    // End of variables declaration//GEN-END:variables
    
}
